﻿namespace StateTheater.Controllers
{
	using System;
	using System.Linq;
	using System.Linq.Expressions;
	using System.Web.Security;
	using Castle.MonoRail.Framework;
	using StateTheater.Helpers;
	using StateTheaterDataModel;
	using StateTheater.Models;
	using Castle.Core;
	using System.Collections.Generic;

	[Layout("default"), Rescue("generalerror")]
	public class MemberController : SmartDispatcherController
	{
		public StateTheaterDataContext db { get; set; }
		public SnitzUtil MemberHelper { get; set; }

		public SnitzViewHelper SnitzViewHelper { get; set; }

		public void Select() { }

		public void Display(int memberid)
		{
			Display(mem => mem.MEMBER_ID == memberid);
		}
		public void Display(string name)
		{
			Display(mem => mem.M_NAME == name);
		}
		void Display(Expression<Func<FORUM_MEMBER, bool>> whereClause)
		{
			var member = db.FORUM_MEMBERs.FirstOrDefault(whereClause);
			PropertyBag["member"] = member;

			if (Context.CurrentUser.IsInRole("Super"))
			{
				PropertyBag["Troupes"] =
					(from tpp in db.TroupePermissions
					 where tpp.MEMBER_ID == member.MEMBER_ID
					 select new
					 {
						 Name = tpp.Troupe.Name,
						 PK = tpp.pk
					 }
					 ).ToArray();

				PropertyBag["hisPowers"] = Roles.GetRolesForUser(member.M_NAME).OrderBy(n => n).ToArray();
				PropertyBag["powers"] = Roles.GetAllRoles();
				PropertyBag["people"] = db.Peoples.Where(p => p.Member_Name == member.M_NAME).ToList();
			}
		}

		[return: JSONReturnBinder]
		[Rescue(typeof(JsonRescueController))]
		public Status AddPower(string member, string power)
		{
			Roles.AddUserToRole(member, power);
			return Status.OK;
		}

		[return:JSONReturnBinder]
		[Rescue(typeof(JsonRescueController))]
		public Status AddTroupe(int memberid, int troupeid)
		{
			if (!db.TroupePermissions.Where(tp => tp.MEMBER_ID == memberid).Any(tp => tp.Troupeid == troupeid))
			{
				var tp = new TroupePermission();
				tp.MEMBER_ID = memberid;
				tp.Troupeid = troupeid;
				db.TroupePermissions.InsertOnSubmit(tp);
				db.SubmitChanges();
				return new StatusPlus(tp.pk.ToString(), tp.Troupe.Name);
			}
			return Status.BAD;
		}

		[return: JSONReturnBinder]
		[Rescue(typeof(JsonRescueController))]
		public Status DeleteMemberPower(string member, string power)
		{
			Roles.RemoveUserFromRole(member, power);
			Response.CachePolicy.SetExpires(DateTime.Now);
			return Status.OK;
		}

		[return: JSONReturnBinder]
		[Rescue(typeof(JsonRescueController))]
		public Status DeleteTroupePermission(int PK)
		{
			var perm = db.TroupePermissions.FirstOrDefault(mp => mp.pk == PK);
			if (perm != null)
			{
				db.TroupePermissions.DeleteOnSubmit(perm);
				db.SubmitChanges();
			}

			return Status.OK;
		}
		public void Pending()
		{
		}

		public void Activate(string key)
		{
			var activated = MemberHelper.ActivatePendingMember(key);
			var member = db.FORUM_MEMBERs.FirstOrDefault(mem => mem.M_KEY == key);
			if (member == null)
			{
				RenderView("ActivationError");
				return;
			}

			PropertyBag["user"] = member;
			PropertyBag["member"] = member;

			if (activated == null)
				RenderView("AlreadyActivated");
			else
				AdminController.MailMessage(member, this, "MemberActivated", PropertyBag);
			// and use Activate view
		}

		public void password2(string name, string email)
		{
			//strSql = "SELECT MEMBER_ID, M_NAME, M_EMAIL FROM " & strMemberTablePrefix & "MEMBERS "
			//strSql = strSql & " WHERE M_NAME = '" & ChkString(Trim(Request.Form("Name")), "SQLString") &"'"
			//strSql = strSql & " AND M_EMAIL = '" & ChkString(Trim(Request.Form("Email")), "SQLString") &"'"
			bool anError = false;
			if (String.IsNullOrEmpty(name))
			{
				PropertyBag["NameError"] = true;
				anError = true;
			}

			if (String.IsNullOrEmpty(email))
			{
				PropertyBag["EmailError"] = true;
				anError = true;
			}

			var member = anError ? null : db.FORUM_MEMBERs.FirstOrDefault(mem => mem.M_NAME == name && mem.M_EMAIL == email);
			PropertyBag["user"] = member;
			PropertyBag["member"] = member;

			if (member == null)
			{
				PropertyBag["MatchError"] = true;
				anError = true;
			}

			if (!anError)
			{
				var pwkey = MemberHelper.GetRandomKey();
				PropertyBag["pwkey"] = pwkey;
				member.M_PWKEY = pwkey;
				db.SubmitChanges();
				AdminController.MailMessage(member, this, "forgotpassword", PropertyBag);
			}
			PropertyBag["Error"] = anError;
		}

		public void ListMembers()
		{
			PropertyBag["SnitzView"] = this.SnitzViewHelper;
		}


		[return: JSONReturnBinder]
		[Rescue(typeof(JsonRescueController))]
		public jqGridPacket<MemberDetailsShort> GetMembers()
		{
			var paging = new jqGridPager(this.Request.Params);
			var q = from mem in db.FORUM_MEMBERs
					select new MemberDetailsShort
					{
						MemberId = mem.MEMBER_ID,
						Name = mem.M_NAME,
						Title = mem.M_TITLE,
						LastPost = mem.M_LASTPOSTDATE,
						LastVisit = mem.M_LASTHEREDATE,
						MemberSince = mem.M_DATE,
						Level = (int)mem.M_LEVEL.GetValueOrDefault(),
						Posts = mem.M_POSTS.GetValueOrDefault(),
						Status  = mem.M_STATUS
					};

			#region SortBy Switch Block
			IOrderedQueryable<MemberDetailsShort> members;
			switch (paging.SortBy + '-' + paging.SortDirect)
			{
				case "Name-asc":
					members = q.OrderBy(pm => pm.Name);
					break;

				case "Name-desc":
					members = q.OrderByDescending(pm => pm.Name);
					break;

				case "Title-asc":
					members = q.OrderBy(pm => pm.Title).ThenBy(pm => pm.Name);
					break;

				case "Title-desc":
					members = q.OrderByDescending(pm => pm.Title);
					break;

				case "LastPost-asc":
					members = q.OrderBy(pm => pm.LastPost).ThenBy(pm => pm.Name);
					break;

				case "LastPost-desc":
					members = q.OrderByDescending(pm => pm.LastPost);
					break;

				case "MemberSince-asc":
				default:
					members = q.OrderBy(pm => pm.MemberSince).ThenBy(pm => pm.Name);
					break;

				case "MemberSince-desc":
					members = q.OrderByDescending(pm => pm.MemberSince);
					break;

				case "LastVisit-asc":
					members = q.OrderBy(pm => pm.LastVisit).ThenBy(pm => pm.Name);
					break;

				case "LastVisit-desc":
					members = q.OrderByDescending(pm => pm.LastVisit);
					break;

				case "Posts-asc":
					members = q.OrderBy(pm => pm.Posts).ThenBy(pm => pm.Name);
					break;

				case "Posts-desc":
					members = q.OrderByDescending(pm => pm.Posts);
					break;
			}
			#endregion

			MemberHelper.WebRoot = this.Context.ApplicationPath;			// TODO: Find an automatic way of doing that.
			var memberPage = paging.AddPaging(members).ToList();
			memberPage.ForEach(pmd =>
				{
					pmd.Title = MemberHelper.DetermineTitle(pmd.Title, pmd.Level, pmd.Posts);
//					pmd.Stars = MemberHelper.DetermineStars(pmd.Level, pmd.Posts);
					pmd.MemberSince = MemberHelper.FixDate(pmd.MemberSince);
					pmd.LastPost = MemberHelper.FixDate(pmd.LastPost);
					pmd.LastVisit = MemberHelper.FixDate(pmd.LastVisit);
				});


			//var page = new jqGridPacket<MemberDetailsShort>(memberPage);
			////page.page = paging.Page;
			////page.records = db.FORUM_MEMBERs.Count();
			////page.total = (page.records + paging.Rows - 1) / paging.Rows;
			//paging.SetResponse(page, db.FORUM_MEMBERs.Count());
			//return page;
			return paging.PackageResponse(memberPage, db.FORUM_MEMBERs.Count());
		}

		[return: JSONReturnBinder]
		[Rescue(typeof(JsonRescueController))]
		public MemberDetails  GetProfile(int memberid)
		{
			var member = (from mem in db.FORUM_MEMBERs
					 where mem.MEMBER_ID == memberid
					 select new MemberDetails
					 {
						 MemberId = mem.MEMBER_ID,
						 Name = mem.M_NAME,
						 MemberSince = mem.M_DATE,
						 Posts = mem.M_POSTS.GetValueOrDefault(),
						 Bio = mem.M_BIO,
						 CoolLink1 = mem.M_LINK1,
						 CoolLink2 = mem.M_LINK2,
						 FirstName = mem.M_FIRSTNAME,
						 Gender = mem.M_SEX,
						 Hobbies = mem.M_HOBBIES,
						 Homepage = mem.M_HOMEPAGE,
						 LastName = mem.M_LASTNAME,
						 Location = mem.M_CITY + " " + mem.M_STATE + " " + mem.M_COUNTRY,
						 Occupation = mem.M_OCCUPATION,
						 Quote = mem.M_QUOTE,
					 }).FirstOrDefault();

			member.MemberSince = MemberHelper.FixDate(member.MemberSince);

			return member;
		}




	}


	}
